package com.kool.kadmin.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis客户端
 *
 * @author luyu
 */
@Component
@Slf4j
public class RedisClient {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * hash赋值
     *
     * @param hash
     * @param key
     * @param value
     */
    public void putHash(String hash, String key, String value) {
        redisTemplate.opsForHash().put(hash, key, value);
    }

    /**
     * hash赋值
     *
     * @param hash
     * @param key
     * @param value
     * @param expire 毫秒
     */
    public void putHash(String hash, String key, String value, long expire) {
        redisTemplate.opsForHash().put(hash, key, value);
        redisTemplate.expire(hash, expire, TimeUnit.MILLISECONDS);
    }

    /**
     * hash取值
     *
     * @param hash
     * @return
     */
    public Map<String, String> getMap(String hash) {
        Set<Object> keys = redisTemplate.opsForHash().keys(hash);
        Map<String, String> ret = new HashMap<>();
        for (Object key : keys) {
            String sKey = (String) key;
            Object value = redisTemplate.opsForHash().get(hash, key);
            ret.put(sKey, (String) value);
        }
        return ret;
    }

    /**
     * 删除hash
     *
     * @param hash
     * @param key
     */
    public void deleteHash(String hash, String key) {
        redisTemplate.opsForHash().delete(hash, key);
    }

    /**
     * 删除key
     *
     * @param key
     */
    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }

    /**
     * kv赋值
     *
     * @param key
     * @param value
     */
    public void setValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * kv赋值
     *
     * @param key
     * @param value
     * @param expire 毫秒
     */
    public void setValue(String key, String value, long expire) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, expire, TimeUnit.MILLISECONDS);
    }

    /**
     * kv取值
     *
     * @param key
     * @return
     */
    public String getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置超时时间
     *
     * @param key
     * @param expire 毫秒
     */
    public void setExpire(String key, long expire) {
        redisTemplate.expire(key, expire, TimeUnit.MILLISECONDS);
    }
}
